/**
 * 功能描述 
 */

define(function (require, exports, module) {
	var aw = require("ajaxwrapper")
	var Form = require("form");
	var store =require("store");
	var tools = require("tools");
	var enmu = require("enums");
	var activeUser = store.get("user");
	var contractAwardDataSvc = require("../store/contractAwardDataSvc");
	var Dialog = require("dialog");
    var instance = {
        initComponent: function (params,widget) {
        	var form = new Form({
        	 parentNode:".J-form",
  			 model:{
				id:"J-form",
				layout: "2_1",
	        	 type : "profile",
	       		 saveaction : function(){
	       			 var pkLong = form.getValue("pkLong");
	       			 var str = form.getValue("balTime");
	       			 var balTime = str.split(" ")[0];
	       			 var unitS = str.split(" ")[1];
	       			 var unit;
	       			 var strs=widget.get("namevalue");
	       			 var names;
	       			 if(strs!=null){
	       				if(strs.indexOf("--")!=-1){
			       			names = strs.split("--")[0]; 
		       			 } 
	       			 } else{
	       				 names = form.$("input[name=name]").val();
	       			 }
	       			 if(unitS == "天/间"){
	       				unit = "Day";
	       			 }else{
	       				unit = "Month";
	       			 }
	       			 var cParams = {};
	       			 if(pkLong){
	       				 //如果是会员
	       				 cParams = {
	       					
       						pkLong: form.getValue("pkLong"),
       						isMem: form.getValue("isMem"),
       						contactNo: form.getValue("contactNo"),
       						productRule:{
       							product: form.getValue("productRule")
       						},
       						productBatch: form.getValue("productBatch"),
       						productType: form.getValue("productType"),
       						number: form.getValue("number"),
       						price: form.getValue("priceSum"),
       						memberCertificates: form.getValue("memberCertificates"),
       						balTime:balTime,
       						unit:unit,
       						signUpDate: form.getValue("signUpDate"), 
    		       			startDate: form.getValue("startDate"), 
    		       			endDate: new Date(form.getValue("endDate")).getTime(), 
    		       			operator: form.getValue("pkOperator"), 
    		       			description: form.getValue("description"),
    		       			servicePoint: widget.get("subnav").getValue("servicePoint"),
    		       			pkTravelContract: form.getValue("pkTravelContract"),
    		       			unitPrice:form.getValue("unitPrice"),
    		       			version: form.getValue("version")
	       				 };
	       			 }else{
	       				 //如果不是会员
	       				cParams = {
       						isMem: true,
	       					member: {
	       						personalInfo: {
//	       							name: form.$("input[name=name]").val(),
	       							name:names,
	       							"idNumber": form.getValue("idNumber"),
           							"sex":form.getValue("sex"),
       								"mobilePhone":form.getValue("mobilePhone"),
    								"birthday":form.getValue("birthday"),
    								"areaAddress":form.getValue("administrative"),
    								"contactAddresses":form.getValue("administrative"),
    								"address":form.getValue("addressDetail"),
    								"version":0
	       						}
	       					},
       						contactNo: form.getValue("contactNo"),
       						productRule:{
       							product: form.getValue("productRule")
       						},
       						productBatch: form.getValue("productBatch"),
       						productType: form.getValue("productType"),
       						number: form.getValue("number"),
       						price: form.getValue("priceSum"),
       						memberCertificates: form.getValue("memberCertificates"),
       						balTime:balTime,
       						unit:unit,
       						signUpDate: form.getValue("signUpDate"), 
    		       			startDate: form.getValue("startDate"), 
    		       			endDate: new Date(form.getValue("endDate")).getTime(), 
    		       			operator: form.getValue("pkOperator"), 
    		       			description: form.getValue("description"),
    		       			servicePoint: widget.get("subnav").getValue("servicePoint"),
    		       			pkTravelContract: form.getValue("pkTravelContract"),
    		       			unitPrice:form.getValue("unitPrice"),
    		       			version: form.getValue("version")
	       				 };
	       			 }
	       			aw.saveOrUpdate("api/travelcontractcharge/saveall",aw.customParam(cParams),function(data){
	       				widget.show([".J-grid"]).hide([".J-form"]);
	       				widget.get("subnav").hide(["back"]).show(["add","search","status","servicePoint","dateRange"]);
	          			widget.get("grid").refresh();
	          			widget.get("servicePoint");
	       			});
	       		 },
	       		 cancelaction : function(){       			 
	       			 widget.show([".J-grid"]).hide([".J-form"]);
	       			 widget.get("subnav").hide(["back"]).show(["add","search","status","servicePoint","dateRange"]);
					 widget.get("grid").refresh();
	       		 },
					items:[{
						title:"会员基本信息",
						children : [{
							name:"name",
							label:"姓名",
							type:"autocomplete",
							url:"api/travelcontract/searchcontractuser",
							keyField:"pkMember",
							queryParamName : "s",
							params:function(str){
								return{
									searchProperties:"personalInfo.name",
									fetchProperties:"pkLong,isMem,personalInfo.*," +
											"personalInfo.contactAddresses.*," +
											"personalInfo.contactAddresses.address.fullName," +
											"personalInfo.contactAddresses.communityData.name," +
											"personalInfo.houseRegister.*"
								}
							},
							format:function(data){
								return data.personalInfo.name + "--" + data.personalInfo.idNumber;
							},
							onItemSelect : function(data){
								form.setValue("name",{
									personalInfo: {
										name: data.personalInfo.name,
										idNumber: data.personalInfo.idNumber
									}
								});
								form.setValue("isMem",data.isMem);
								form.setValue("pkLong",data.pkLong);
								form.setValue("idNumber",data.personalInfo.idNumber);
								form.setValue("sex",data.personalInfo.sex.key);	
								form.setValue("mobilePhone",data.personalInfo.mobilePhone);
								var birthdays = data.personalInfo.birthday;
								if(birthdays){
									var birthday = moment(birthdays).format('YYYY-MM-DD');
									var age = tools.getAgeByBirthdate(birthday);
									form.setValue("birthday",birthday);
									form.setValue("age",age);
								}
								//为地址赋值
								if(data.isMem){
									//如果是会员，则取contactAddresses.address,contactAddresses.detailAddress
									//var contactAddresses = data.personalInfo;
									/*if(contactAddresses && contactAddresses.length != 0){
										if(contactAddresses[0].address){
											form.setValue("administrative",contactAddresses.address);
										}
										form.setValue("addressDetail",contactAddresses.detailAddress);
									}*/
									form.setValue("administrative",data.personalInfo.houseRegister);
									form.setValue("addressDetail",data.personalInfo.address);
								}else{
									//如果是意向客户，则取personalInfo.houseRegister,personalInfo.address
									if(data.personalInfo.houseRegister){
										form.setValue("administrative",data.personalInfo.houseRegister);
									}
									form.setValue("addressDetail",data.personalInfo.address);
								}
								
								form.setReadonly(["idNumber","sex",
				                  "mobilePhone","birthday","administrative","addressDetail","age"],true);
							},
							onNoMatch: function(){
								form.setValue("isMem", true);
								form.setReadonly(["idNumber","sex",
				                  "mobilePhone","birthday","administrative","addressDetail","age"],false);
							},
							mustMatch: false,
							validate: ["required"]					
						},{
							name: "pkLong",
							type: "hidden"
						},{
							name: "isMem",
							type:"hidden"
						},{
							name:"idNumber",
							label:"身份证号",
							validate: ["required"],
							exValidate: function(value) {
								var reg = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/;
								if(!reg.test(value)){
									return "请输入正确的身份证号！";
								}else{
									return true;
								}
	                        },
							events: {
								"blur": function(e){
									if(e.target.value){
										var birthday = tools.getBirthdateByIdNo(e.target.value);
										var age = tools.getAgeByBirthdate(birthday);
										if(birthday.length==10){
											form.setValue("birthday",birthday);
											form.setValue("age",age);
										}
									}
								}
							}
						},{
				            name: "sex",
				            label:"性别",
				            type: "radio",
				            validate: ["required"],
	                        list : enmu["com.eling.elcms.basedoc.model.Sex"]
						},{
							name:"mobilePhone",
							label:"联系电话",
							validate: ["required"],
						},{
							name:"birthday",
							label:"出生日期",
							type: "date",
//							events: {
//	                            "blur": function(e) {
//	                            	if(e.target.value){
//	                            		var age = tools.getAgeByBirthdate(e.target.value);
//		                                form.setValue("age", age);
//	                            	}
//	                            }
//	                        }
						},{
							name:"age",
							label:"年龄",
						},{
							name:"administrative",
							label:"省/市/区（县）",
							type: "place",
							"break": true
						},{
							name:"addressDetail",
							label:"详细地址",
							"break": true
						}]
					},{
						title: "合同签约",
						children : [{
							name:"contactNo",
							label:"合同号",
							validate: ["required"],
							exValidate: function(value) {
	                            var reg = /^[A-Za-z0-9\-\/\\\.\(\)\~\<\>\[\]\{\}]{1,20}$/;
	                            if (!reg.test(value)) {
	                                return "只能输入数字、字母和特殊字符,最多20位";
	                            } else {
	                                return true;
	                            }
	                        }
						},{
							name:"productRule",
							label:"产品",
							type:"select",
							url:"api/product/query",
							key:"pkProduct",
							value:"name",
							validate: ["required"],
							events: {
	                            "click": function(e) {
	                               //查询产品类型
	                            	contractAwardDataSvc.getproductType(e.target.value,function(productType){
	                            		form.setData("productType", productType);
		   		                   });
	                            }
	                        }                        
						},{
							name:"productType",
							label:"产品类型",
							type:"select",
							key:"pkProductType",
							value:"name",
							events: {
	                            "click": function(e) {
	                               //查询产品批次
	                            	var pkProduct = form.getValue("productRule");
	                            	var pkTravelContract = form.getValue("pkTravelContract");
	                               // if(!pkTravelContract){
		                            	contractAwardDataSvc.getproductBatch(pkProduct,e.target.value,function(data){
			   		                	  /* var startDate = form.getValue("startDate");
			   		                	   var startDate = moment().format("YYYY-MM-DD");
			   		                	   var startYear = startDate.split("-")[0];
			   		                	   var startMonth = startDate.split("-")[1];
			   		                	   var startDay = startDate.split("-")[2];
			   		                	   var endDaYrar = Number(startYear) + Number(data[0].validity);
			   		                	   var endDate = endDaYrar+ "-" + startMonth + "-" + startDay;
			   		                	   form.setValue("endDate", endDate);
			   		                	   form.setValue("prices", data[0].price);
			   		                	   form.setValue("balTimeSum",data[0].liveDays);
			   		                	   form.setValue("unit",data[0].unit.key == null ? "" : data[0].unit.value);
			   		                	   form.setValue("seal",data)*/
			   		                	   form.setData("productBatch", data);
			   		                   });
	                               }
	                          //  }
	                        },   
							validate: ["required"]
						},{
							name:"productBatch",
							label:"产品批次",
							type:"select",
							key:"pkProductBatch",
							value:"name",
							events:{
								"click":function(e){
									   //var pkProductBatch = form.getValue("productBatch");
									  // var pkProduct = form.getValue("pkProductRule");
									   var pkTravelContract = form.getValue("pkTravelContract");
									   var pkProductType = form.getValue("productType");
									   var number = $(":input[name='number']").val();
		                               //if(!pkTravelContract){
		                            	   contractAwardDataSvc.getproductDetail(pkProductType,e.target.value,function(data){
											   var startDate = form.getValue("startDate");
				   		                	   var startDate = moment().format("YYYY-MM-DD");
				   		                	   var startYear = startDate.split("-")[0];
				   		                	   var startMonth = startDate.split("-")[1];
				   		                	   var startDay = startDate.split("-")[2];
				   		                	   var endDaYrar = Number(startYear) + Number(data.validity);
				   		                	   var endDate = endDaYrar+ "-" + startMonth + "-" + startDay;
				   		                	   form.setValue("endDate", endDate);
				   		                	   form.setValue("prices", data.price);
				   		                	   form.setValue("balTimeSum",data.liveDays);
				   		                	   if(data.unit==null ? "" : data.unit){
				   		                		   form.setValue("unit",data.unit.key == null ? "" : data.unit.value);
				   		                	   }
				   		                	 //  form.setValue("seal",data.seal);
				   		                	if(number!=null && number!=""){
				                            	 var balTime = form.getValue("balTimeSum");
			                            		 var prices = form.getValue("prices");
			                            		 var unit = form.getValue("unit");
					                             var priceSum = number*prices;
					                             var balTimes = number*balTime;
					                             form.setValue("priceSum", parseFloat(priceSum).toFixed(2)); 
					                             form.setValue("balTime", balTimes +" " + unit);
					                             form.setValue("unitPrice",parseFloat(priceSum/balTimes).toFixed(2));
				                            }
		                            	   });
		                             //  }
		                             
		                               /*if(number!=null && number!="" && pkTravelContract){
		                                	var pkProduct = form.getValue("productRule");
		                                	var productType = form.getValue("productType");
		                                	 contractAwardDataSvc.getproductBatch(pkProduct,productType,function(data){
			                                	form.setValue("prices", data[0].price);
			                                	form.setValue("balTime", data[0].balTime);
		                            		 var prices = form.getValue("prices");
		                            		 var balTime = form.getValue("balTime");
		                            		 var unit = form.getValue("unit");
				                             var priceSum = number*prices;
				                             var balTimes = number*balTime;
				                             form.setValue("priceSum", parseFloat(priceSum).toFixed(2)); 
				                             form.setValue("balTime", balTimes +" " + unit);
				   		                   });
		                               }*//*else if(number!=null && number!=""){
			                            	 var balTime = form.getValue("balTimeSum");
		                            		 var prices = form.getValue("prices");
		                            		 var unit = form.getValue("unit");
				                             var priceSum = number*prices;
				                             var balTimes = number*balTime;
				                             form.setValue("priceSum", parseFloat(priceSum).toFixed(2)); 
				                             form.setValue("balTime", balTimes +" " + unit);
			                            }*/
		                               
								}
							},
						validate: ["required"],
						},{
							name:"number",
							label:"购买份数",
							type:"text",
							validate: ["required"],
							exValidate: function(value) {
	                            var reg = /^[0-9]*[1-9][0-9]*$/;
	                            if (!reg.test(value)) {
	                            	form.setValue("priceSum", ""); 
	                                return "不可输入0，负数，小数，特殊字符，汉字";
	                            } else {
	                                return true;
	                            }
	                        },
							events: {
	                            "change": function(e) {
	                                var pkTravelContract = form.getValue("pkTravelContract");
	                                var num = e.target.value;
	                                /*if(pkTravelContract){
	                                	var pkProduct = form.getValue("productRule");
	                                	var productType = form.getValue("productType");
	                                	 contractAwardDataSvc.getproductBatch(pkProduct,productType,function(data){
		                                	form.setValue("prices", data[0].price);
		                                	form.setValue("balTime", data[0].balTime);
	                            		 var prices = form.getValue("prices");
	                            		 var balTime = form.getValue("balTime");
	                            		 var unit = form.getValue("unit");
			                             var priceSum = num*prices;
			                             var balTimes = num*balTime;
			                             form.setValue("priceSum", parseFloat(priceSum).toFixed(2)); 
			                             form.setValue("balTime", balTimes +" " + unit);
			   		                   });
		                            }*///else{
		                            	 var balTime = form.getValue("balTimeSum");
	                            		 var prices = form.getValue("prices");
	                            		 var unit = form.getValue("unit");
			                             var priceSum = num*prices;
			                             var balTimes = num*balTime;
			                             form.setValue("priceSum", parseFloat(priceSum).toFixed(2)); 
			                             form.setValue("balTime", balTimes +" " + unit);
			                             form.setValue("unitPrice",parseFloat(priceSum/balTimes).toFixed(2));
		                            }
	                            }	                            
	                       // }
						},{
							name:"priceSum",
							label:"金额（元）",
							readonly:true,
						},{
							name:"prices",
							type:"hidden",
							defaultValue: 0
						},{
							name:"balTimeSum",
							type:"hidden",
							defaultValue: 0
						},{
							name:"memberCertificates",
							label:"会员证号",
							validate: ["required"],
							exValidate: function(value) {
								var reg = /^[A-Za-z0-9\-\/\\\.\(\)\~\<\>\[\]\{\}]{1,20}$/;
	                            if (!reg.test(value)) {
	                            	return "只能输入数字、字母和特殊字符,最多20位";
	                            } else {
	                                return true;
	                            }
	                        }
						},{
							name:"balTime",
							label:"居住期限",
							readonly:true,
						},{
							name:"unit",
							label:"期限单位",
							type :"hidden",
							options : enmu["com.eling.elcms.travel.model.ProductRuleDetail.Unit"],
							readonly:true
						},{
							name:"signUpDate",
							label:"签约日期",
							type:"date",
							defaultValue:moment(),
							mode:"YYYY-MM-DD"	,
							readonly:true,
						},{
							name:"startDate",
							label:"开始日期",
							type:"date",
							defaultValue:moment(),
							mode:"YYYY-MM-DD",					
							validate: ["required"]
						},{
							name:"endDate",
							label:"终止日期",
							type:"date",
							mode:"YYYY-MM-DD",
							readonly:true,
						},{
							name:"operator",
							label:"销售顾问",
							readonly:true,
							defaultValue:activeUser.name
						},{
							name:"pkOperator",
							type:"hidden",
							defaultValue: activeUser.pkUser
						},{
							name:"description",
							label:"备注",
							defaultValue : "",
							required:true,
							type:"textarea",
							"break": true,
							exValidate:function(value){		
								if(value.length > 100){
									return "不能超过100个字";
								}else{
									return true;
								}
							}
						},{
							name:"unitPrice",
							label:"单价",
							type:"hidden",
						},{
							name:"version",
							type:"hidden",
							defaultValue: "0"
						},{
							name:"pkTravelContract",
							type:"hidden"
						}]
					}]
  			 	}
           });
        widget.set("form",form);
       }
    };
    module.exports = instance;
});
